package com.batsoft.redis;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @author <a href="mailto:HelloHeSir@gmail.com">Mr_He</a>
 */
@Getter
@Setter
@Component
@Configuration
@EnableConfigurationProperties({RedisProperties.class})
public class RedisConfig {

    @Autowired
    private RedisProperties redisPro;

    @Bean
    public JedisCluster jedisCluster(JedisPoolConfig jedisPoolConfig) {
        Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();

        for (RedisConnHost value : redisPro.getSource().values()) {
            HostAndPort hostAndPort = new HostAndPort(value.getHost(), value.getPort());
            hostAndPortsSet.add(hostAndPort);
        }

        return new JedisCluster(hostAndPortsSet, jedisPoolConfig);
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        // Jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲连接数
        jedisPoolConfig.setMaxIdle(redisPro.getMaxIdle());
        // 最大连接数
        jedisPoolConfig.setMaxTotal(redisPro.getMaxTotal());
        //最小空闲连接数
        jedisPoolConfig.setMinIdle(redisPro.getMinIdle());
        // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(redisPro.getTimeout());
        //对拿到的connection进行validateObject校验
        jedisPoolConfig.setTestOnBorrow(true);
        return jedisPoolConfig;
    }

}